import BLELocker from '../BLELocker.js';
import CONSTANT_DATA from '../util.js';

var util = require("util.js");
var connetToDfu = require("connect-to-dfu.js");
var connectCmd = require("connect-cmd.js");
var dfuDevName = "DfuTarg";
const app = getApp()

var isFindDev = false;
var isFindDevLog = true;
var isDfuFlg = false;
var isScanTimeout = true;

var scanRetryCount = 1;
//未发现任何设备的时候重试一次
var noFindOneRetryCount = 1;
var isAlreadyConnectedCount = 0;
var scanTimoutTimer = null;
var _AdapterRespTime = 5000;
var openBlueAdapterTimer = null;

var scanDevice = function scanDevice(mac) {
  console.log("开始扫描--->", mac);
  wx.showLoading({
    title: '查找中...',
  })
  isFindDev = false;  
  console.log("开始打开适配器--->", mac);
  isAlreadyConnectedCount = 0;

  if (scanTimoutTimer) {
    clearTimeout(scanTimoutTimer);
    scanTimoutTimer = null;
  }

  wx.getBluetoothAdapterState({
    success: function (res) {
      if (res && res.discovering) {
        //正在搜索的取消搜索
        wx.stopBluetoothDevicesDiscovery({ success(res) { } });
      }
      if (res && res.available) {
        connectBox(mac);
      } else {
        openAdapterConnectBox(mac);
      }
    },
    fail: function (err) {
      openAdapterConnectBox(mac);
    }
  })


}

//打开适配器后进行连接
function openAdapterConnectBox(mac) {
  wx.openBluetoothAdapter({
    success: function (res) {
      connectBox(mac)
    },
    fail: function (err) {
      console.log("蓝牙适配器打开失败,重试扫描连接", err );
      if(!app.globalData.beforeConIsGateway) {        
        let macAddr =  mac.indexOf("DK") == 0 ? mac.substring(2) : mac;
        console.log("蓝牙适配器打开失败,直接走网关连接,mac=",macAddr);
      }else {
        wx.showModal({
          title: '提示',
          showCancel:false,
          content: '请重新打开蓝牙',
          success (res) {
          }
        })
      }
    }

  })
}

//连接控制盒
function connectBox(mac) {
  wx.removeStorageSync('retryOpenBlueAdapterCount');
  wx.showLoading({
    title: '适配器开启',
  })
  let device = getDevFromCacheByMac(mac);
  if (device && app.globalData.conRetryCount > 1) {
    console.log("从缓存获取到设备,直接进行连接", mac)
    executeCon(device, mac);
  } else {
    console.log("开始搜索设备---->");
    startScanBlue(mac);
  }
}

function startScanBlue(blueName){
  wx.getBluetoothDevices({
    success: function (res) {
      console.log(res)
      let devices = res.devices;
      devices.forEach(device => {
        console.log("蓝牙名：" + device.name)
        if (device.name == blueName || device.localName == blueName) {
            console.log("存在已搜索到的设备,关闭连接---->",blueName);
            let deviceId = device.deviceId;
            wx.closeBLEConnection({
              deviceId: deviceId,
              success: function (res) {
              },
              fail: function (err) {
              },
              complete:function(){
              }
            });
        }
      });
      setTimeout(()=>{
        scanBlue(blueName);
      },100);
    }
  })
}

//未搜索到任何设备关闭搜索，同时关闭蓝牙适配器
function stopDiscoveryAndCloseAdapter() {
  if (wx.canIUse('offBluetoothDeviceFound')) {
    wx.offBluetoothDeviceFound(function () {
      console.log("取消监听")
    });
  }
  wx.stopBluetoothDevicesDiscovery({
    success: function (res) { },
    complete: function () {
      wx.closeBluetoothAdapter({
        success: function (res) { },
      });
    }
  });
  if (app.globalData._that) {
    wx.showModal({
      title: '提示',
      showCancel:false,
      content: '搜索不到任何设备，开关蓝牙重试',
      success (res) {
      }
    })
  } else {
    wx.showModal({
      title: '温馨提示',
      content: '请检查定位服务是否已打开',
    })
  }
}

//搜索蓝牙
function scanBlue(mac) {
  //扫描未收到任何设备的时长限制
  console.log('开始扫描--', scanRetryCount, scanTimoutTimer == null);
  clearTimeout(scanTimoutTimer);
  scanTimoutTimer = setTimeout(function () {
    util.recordLog(CONSTANT_DATA.err_type.new_con_scan_null, "扫描api调用超时:" + mac + ":" + noFindOneRetryCount + ":" + scanRetryCount);
    if (wx.canIUse('offBluetoothDeviceFound')) {
      wx.offBluetoothDeviceFound(function () {
        console.log("取消监听")
      });
    }
    wx.getLocation({
      type: 'wgs84',
      success(res) {
        if (noFindOneRetryCount > 0) {
          noFindOneRetryCount--;
          wx.stopBluetoothDevicesDiscovery({
            success: function (res) { },
            complete: function () {
              scanDevice(mac);
            }
          });
          if (app.globalData.isLeaseCon) {
            wx.showLoading({
              title: '重试扫描...',
            })
          }
        } else {
          stopDiscoveryAndCloseAdapter();
        }
      },
      fail(res) {
        stopDiscoveryAndCloseAdapter();
      }
    })
  }, 5000);

  wx.startBluetoothDevicesDiscovery({
    // services: ["FEE7"],//过滤，只搜索微信硬件设备
    allowDuplicatesKey: true,
    interval: 0.1,
    powerLevel:'high',
    success: function (res) {
      console.log("开始扫描设备...." + mac, res);
      wx.showLoading({
        title: '扫描中..',
        mask: true
      });

      bleCallback(mac);

    },
    fail: function (err) {

      wx.showModal({
        title: '提示',
        showCancel:false,
        content: '扫描调用失败',
        success (res) {
        }
      })

    }
  })
}

function bleCallback(mac) {  
  let scanEquTimer = setTimeout(function () {
    
    if (app.globalData.isLeaseCon) {
      let descStr = !app.globalData.isFindTimeout ? '发现设备超时,重试中...' : '发现设备超时,请确认再设备旁,再扫码重试下';
      wx.showModal({
        title: '提示',
        showCancel:false,
        content: descStr,
        success (res) {
        }
      })
      if(app.globalData.isFindTimeout) {
        stopDiscoveryAndCloseAdapter(); 
        setTimeout(function (res) {
          wx.hideLoading({
            success: (res) => {},
          })
        }, 1500);
        wx.showModal({
          title: '提示',
          showCancel:false,
          content: '扫描超时',
          success (res) {
          }
        })
      }else {
        app.globalData.isFindTimeout = true;
        if (wx.canIUse('offBluetoothDeviceFound')) {
          wx.offBluetoothDeviceFound(function () {
            console.log("取消监听")
          });
        }
        wx.stopBluetoothDevicesDiscovery({
          success: function (res) { 
  
            wx.closeBluetoothAdapter({
              success: function (res) {
                setTimeout(function (res) {
                  wx.openBluetoothAdapter({
                    success: function (res) {
                      setTimeout(function (res) {
                         scanBlue(mac);
                         wx.showToast({
                           title: '扫描超时',
                         })
                      }, 10000);
                    },
                    fail: function (err) {
                      wx.hideLoading({
                        success: (res) => {},
                      })
                      wx.showToast({
                        title: '扫重试03',
                      })
                    }
                  })  
                }, 500);
              },
              fail:function(err){
                wx.hideLoading({
                  success: (res) => {},
                })
                wx.showToast({
                  title: '扫重试02',
                })
              }
            });
  
          },        
          fail: function(){
            wx.hideLoading({
              success: (res) => {},
            })
            wx.showToast({
              title: '扫重试01',
            })
          }
        }); 
      }      
    }

  }, 5000);
  clearTimeout(scanTimoutTimer);

  wx.onBLEConnectionStateChange(function (res) {//链接状态回调
      console.log("连接状态" + res.connected, res);   
  });


  isScanTimeout = true;
  //搜索到的设备记录
  app.globalData.findDevs = new Array();
  let startScanTime = new Date().getTime();
  let findI = 0;
  wx.onBluetoothDeviceFound(function (res) {
    if(findI == 0) {
      clearTimeout(scanEquTimer);
      findI++;
    }
    
    var devices = res.devices;
    //判断搜索是否超时
    let curTime = new Date().getTime();
    //第一次超时5秒，重试一次8秒
    let scanTimeout = scanRetryCount == 1 ? 5000 : 8000;
    //超时且没有找到设备，防止连接超时同时造成搜索超时
    if (curTime - startScanTime > scanTimeout && isScanTimeout && !isFindDev) {
      isScanTimeout = false;
      //搜索超时，退出
      console.log("搜索超时退出------>", curTime, startScanTime);

      if (wx.canIUse('offBluetoothDeviceFound')) {
        wx.offBluetoothDeviceFound(function () {
          console.log("取消监听")
        });
      }

      wx.stopBluetoothDevicesDiscovery({
        success: function (res) {
          console.log("搜索停止成功,重试连接", mac);
          scanTimoutRetryCon(mac);
        },
        fail: function (err) {
          console.log("搜索停止失败,重试连接", mac);
          scanTimoutRetryCon(mac);
        }
      });
      
      wx.hideLoading();

      //关闭已连接的设备，防止连接导致搜索不到设备
      wx.getConnectedBluetoothDevices({
        success: function (res) {
          console.log("蓝牙连接获取成功---->", res);          
          let conDevices = res.devices;
          if (conDevices && conDevices.length > 0 && conDevices[0].deviceId) {
            console.log("存在连接的蓝牙---->");
            wx.closeBLEConnection({
              deviceId: conDevices[0].deviceId,
              success: function (res) {
              },
              fail: function (err) {
              },
              complete:function(){
                getApp().globalData.disconnectLineNum = "connect725";
              }
            });
          } 
        },
        fail: function (err) {
          if(openBlueAdapterTimer) {
            clearTimeout(openBlueAdapterTimer);
          }          
          console.log("蓝牙连接获取失败---->", err);         
        }
      });

      return;
    }

    if (isFindDev) {
      if (isFindDevLog) {
        console.log("已找到设备")
      }
      isFindDevLog = false;


      if (wx.canIUse('offBluetoothDeviceFound')) {
        wx.offBluetoothDeviceFound(function () {
          console.log("取消监听")
        });
      }

      //找到设备后将重试次数标记恢复
      scanRetryCount = 1;
      //未发现任何设备的时候重试一次
      noFindOneRetryCount = 1;
      console.log("已搜索到设备")
      return;
    }

    if (devices == null || devices == undefined) {
      console.log("搜索的设备为空",res);
      return;
    }

    if (!app.globalData.isLeaseCon && isDfuFlg) {
      mac = dfuDevName;
    }
    if (devices.deviceId) {
      dev = findConDev(devices, mac);
      if (dev != null) {
        isScanTimeout = false;
        isFindDev = true;
        //匹配到设备可以关闭搜索
        console.log("匹配设备结束开始连接设备", dev, mac);
        wx.showLoading({
          title: '连接中...',
        })
        executeCon(dev, mac);

        if (wx.canIUse('offBluetoothDeviceFound')) {
          wx.offBluetoothDeviceFound(function () {
            console.log("取消监听")
          });
        }
        //找到设备后将重试次数标记恢复
        scanRetryCount = 1;
        //未发现任何设备的时候重试一次
        noFindOneRetryCount = 1;

        return;
      }
    } 

    if(devices) {
      //查询设备列表是否存在要找的设备
      findDevFromScanDevices(devices,mac);
    }
    if(devices.devices) {
      //之前代码存在，但看文档不应该存在此种情况，为了程序健壮保留此判断
      findDevFromScanDevices(devices.devices,mac);
    }            

  })
  
}

function findDevFromScanDevices(devices,mac){
     //搜索到的蓝牙设备回调，对应可以将相关信息显示在界面上
     for (var i = 0; i < devices.length; i++) {
      var dev = null;
      if (!app.globalData.isLeaseCon && app.globalData.allowUpgradeOtherMac) {
        //允许升级旁边的控制盒
        if (!app.globalData.otherMacs || app.globalData.otherMacs.length == 0) {
          console.log("周围不存在控制盒------>");
          wx.stopBluetoothDevicesDiscovery({});
          wx.hideLoading();
          return;
        }
        for (var j = 0; j < app.globalData.otherMacs.length; j++) {
          let otherMac = "DK" + app.globalData.otherMacs[j];
          dev = findConDev(devices[i], otherMac);
          if (dev != null) {
            console.log("搜到周围设备mac=", otherMac);
            //清空掉其他mac地址，防止重复的影响
            app.globalData.otherMacs = [];
            app.globalData.allowUpgradeOtherMac = false;
            mac = otherMac;
            break;
          }
        }
      } else {
        dev = findConDev(devices[i], mac);
      }

      if (dev != null) {
        isScanTimeout = false;
        isFindDev = true;
        //匹配到设备可以关闭搜索
        console.log("匹配设备结束开始连接设备", dev, mac);
        if (app.globalData.isLeaseCon) {          
          wx.showLoading({
            title: '连接中...',
          })
        }
        executeCon(dev, mac);

        if (wx.canIUse('offBluetoothDeviceFound')) {
          wx.offBluetoothDeviceFound(function () {
            console.log("取消监听")
          });
        }

        scanRetryCount = 1;
        //未发现任何设备的时候重试一次
        noFindOneRetryCount = 1;

        break;
      }
    }
}

function executeCon(dev, mac) {
  if (app.globalData.isLeaseCon) {
    app.globalData.conTimeoutTimer = setTimeout(function () {
      if (!app.globalData.conIsSuc) {
        wx.showModal({
          title: '提示',
          showCancel:false,
          content: '连接超时，请关闭蓝牙再打开后重试',
          success (res) {
          }
        })
      }
    }, 90000);
    //租赁连接
    console.log("租赁连接开始");
    wx.showLoading({
      title: '开始连...',
    })
    wx.getConnectedBluetoothDevices({
      success: function (res) {
        let conDevices = res.devices;
        if (conDevices && conDevices.length > 0 && conDevices[0].deviceId == dev.deviceId) {
          console.log("蓝牙已经连接---->");
          connectCmd.getSerciceAndNotify(dev, 100);
        } else {
          console.log("蓝牙未连接--开始连接", mac);
          connectCmd.connectLease(dev, mac, scanDevice);
        }
      },
      fail: function (err) {
        console.log("获取连接失败--开始连接", mac);
        connectCmd.connectLease(dev, mac, scanDevice);
      }
    })
  } else {
    if (mac != dfuDevName) {
      connetToDfu.connectDevice(dev, function () {
        upgradeDfu();
        if (getApp().globalData.isBeforeLeaseUpgrade) {
          wx.showLoading({
            title: '升级中..',
            mask: true
          });
        }
      });
    } else if (mac == dfuDevName) {
      isDfuFlg = false;
      dfuUpgrade.connectDfuDevice(dev, null);
    }
  }

}

//判断搜索到的设备是否为要找的设备
function findConDev(device, mac) {
  if (isFindDev) {
    //已找到设备
    console.log("已找到设备。。。", mac);
    isDfuFlg = false;
    return null;
  }

  let devName = null;
  //避免同一个设备多次重复回调
  if (device.name) {
    devName = device.name;
  }else if (device.localName) {
    devName = device.localName;
  }

  if(devName && app.globalData.findDevs.indexOf(devName) == -1) {
    app.globalData.findDevs.push(devName);
  }
  
  //蓝牙广播数据
  if (devName == mac) {
    console.log("【搜索到蓝牙设备】匹配到设备------》", device, advertisData, mac)
    return device;
  }
  
  //自定义广播数据
  let advertisData = device.advertisData ? ab2hex(device.advertisData) : null;
  if (advertisData) {
    let head = advertisData.substring(0, 4);
    if (head > 5701) {
      let adMacName = advertisData.substring(4, 16);
      let dname = 'DK' + adMacName.toUpperCase();

      let logDevName = "bc:"+dname;
      if(app.globalData.findDevs.indexOf(logDevName) == -1) {
        app.globalData.findDevs.push(logDevName);
      }      

      if (mac === dname) {
        console.log("从自定义广播中匹配到mac", advertisData);
        return device;
      }
    }
    if (advertisData.length >= 16) {
      let devName = advertisData.substring(4, 6) + ":" + advertisData.substring(6, 8) + ":" + advertisData.substring(8, 10) + ":" + advertisData.substring(10, 12) + ":" + advertisData.substring(12, 14) + ":" + advertisData.substring(14, 16);
      devName = devName.toUpperCase();
      let logDevName = "bc:"+devName;
      if(app.globalData.findDevs.indexOf(logDevName) == -1) {
        app.globalData.findDevs.push(logDevName);
      }      
      if (mac === devName) {
        console.log("从自定义广播中匹配到mac", advertisData,devName);
        return device;
      }
    }
  }

  return null;
}

//从缓存获取连接的设备信息
function getDevFromCacheByMac(mac) {
  if (mac) {
    let m = mac.indexOf("DK") == 0 ? mac.substring(2) : mac;
    return wx.getStorageSync(m);
  } else {
    return null;
  }
}

// ArrayBuffer转16进度字符串示例
function ab2hex(buffer) {
  try {
    var hexArr = Array.prototype.map.call(
      new Uint8Array(buffer),
      function (bit) {
        return ('00' + bit.toString(16)).slice(-2)
      }
    )
  } catch (ex) {
    return null;
  }
  return hexArr.join('');
}

function upgradeDfu() {
  isDfuFlg = true;
  app.globalData.allowUpgradeOtherMac = false;
  console.log("开始升级文件包..." + dfuDevName);
  //先关闭蓝牙适配器，成功失败均进行扫码连接
  wx.closeBluetoothAdapter({
    success: function (res) {
      console.log("关闭适配器成功..." + dfuDevName);
      scanDevice(dfuDevName);
    },
    fail: function (err) {
      console.log("关闭适配器失败..." + dfuDevName);
      scanDevice(dfuDevName);
    }
  });
}

function scanTimoutRetryCon(mac) {
  let errType = scanRetryCount == 1 ? CONSTANT_DATA.err_type.new_con_scan_timeout : CONSTANT_DATA.err_type.new_con_scan_second_timeout;
  let findDevsStr = JSON.stringify(app.globalData.findDevs);
  let isConFlg = getApp().globalData.devConnected;
  wx.getLocation({
    type: 'wgs84',
    success(res) {
      let err = res ? JSON.stringify(res) : "";
      util.recordLog(errType, "搜索超时:获取定位成功:" + mac + ":" + app.globalData.isLeaseCon + ":" + isAlreadyConnectedCount + ":" + scanRetryCount+":"+findDevsStr+":"+err+":"+isConFlg);
    },
    fail(res) {
      let err = res ? JSON.stringify(res) : "";
      util.recordLog(errType, "搜索超时:获取定位失败:" + mac + ":" + app.globalData.isLeaseCon + ":" + isAlreadyConnectedCount + ":" + scanRetryCount+":"+findDevsStr+":"+err+":"+isConFlg);
    }
  })
  
  wx.getConnectedBluetoothDevices({
    success: function (res) {
      let conDevices = res.devices;
      if (conDevices && conDevices.length > 0 && conDevices[0].deviceId) {
        console.log("存在连接的蓝牙---->");
        wx.closeBLEConnection({
          deviceId: conDevices[0].deviceId,
          success: function (res) {
            scanTimeoutRetryExcute(mac);
          },
          fail: function (err) {
            scanTimeoutRetryExcute(mac);
          },
          complete:function(){
            getApp().globalData.disconnectLineNum = "connect625";
          }
        });
      } else {
        scanTimeoutRetryExcute(mac);
      }
    },
    fail: function (err) {
      scanTimeoutRetryExcute(mac);
    }
  });
}
function scanTimeoutRetryExcute(mac) {
  if (scanRetryCount > 0) {
    setTimeout(function () {
      scanRetryCount--;
      startCon(mac);
    }, 200);
  } else {
    //未搜索到任何设备关闭搜索，同时关闭蓝牙适配器
    wx.stopBluetoothDevicesDiscovery({
      success: function (res) { },
      complete: function () {
        wx.closeBluetoothAdapter({
          success: function (res) { },
        });
      }
    });
    wx.showModal({
      title: '提示',
      showCancel:false,
      content: '未搜索到设备',
      success (res) {
      }
    })
  }
}

function startCon(mac) {
  //连接重试1次
  app.globalData.conRetryTotalCount = 1;
  app.globalData.conRetryCount = app.globalData.conRetryTotalCount;
  console.log("开始新连接1.0....");
  let openBlueAdapterTimer = setTimeout(function () {
    wx.showToast({
      title: '无响应重试',
    })
    wx.closeBluetoothAdapter({
      success: function (res) { },
    });
  },8000)

  wx.openBluetoothAdapter({
    success: function (res) {
      if(openBlueAdapterTimer) {
        clearTimeout(openBlueAdapterTimer);
      } 
      wx.removeStorageSync('retryOpenBlueAdapterCount');
      startScanMac(mac);
    },
    fail: function (err) {
      wx.showToast({
        title: '重开蓝牙',
      })
    }
  })

}

function startScanMac(mac) {
  setTimeout(function () {
    scanDevice(mac);
  }, 100);
}




module.exports = {
  scanDevice: scanDevice,
  upgradeDfu: upgradeDfu,
  startCon: startCon
}
